<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <!-- 图片，用来展示用户选择的头像 -->
      <img v-if="avatar" :src="avatar" alt="" />
      <img v-else src="../../../assets/images/avatar.jpg" alt="" />

      <!-- 按钮区域 -->
      <div class="btn-box">
      <input type="file"
       style="display:none"
       accept="image/*"
       @change="imgChange"
        ref="inp">
        <el-button type="primary" icon="el-icon-plus" @click="$refs.inp.click()">选择图片</el-button>
        <el-button type="success" icon="el-icon-upload" :disabled="!avatar" @click="hUpload">上传头像</el-button>
      </div>
    </div>
  </el-card>
</template>

<script>
export default {
  name: 'UserAvatar',
  data () {
    return {
      avatar: ''
    }
  },
  methods: {
    imgChange (e) {
      // console.dir(e.target)
      const file = e.target.files[0]
      if (file) {
        const fr = new FileReader()
        fr.readAsDataURL(file)
        fr.onload = (e) => {
          // console.log(e.target.result)
          this.avatar = e.target.result
        }
      } else {
        this.avatar = ''
      }
    },
    async hUpload () {
      const { data: res } = await this.$axios.patch('/my/update/avatar', { avatar: this.avatar })
      if (res.code !== 0) return this.$message.error('提交失败')
      this.$message.success('提交成功')
      this.$store.dispatch('user/getUserInfo')
      this.avatar = ''
    }
  }
}
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
}
</style>
